package com.wongleoi.weather_demo.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.wongleoi.weather_demo.CityWeatherListAdapter
import com.wongleoi.weather_demo.R
import com.wongleoi.weather_demo.WeatherApplication
import com.wongleoi.weather_demo.databinding.WeatherInfoBinding
import com.wongleoi.weather_demo.model.CityBean

/**

 * @author wongleoi

 * @classname WeatherListFragment.kt

 * @describe  天气列表

 * @time 2022/7/15 16:34

 */
class WeatherListFragment : Fragment() {

    private var mLayoutManager: LinearLayoutManager? = null
    private var pagingAdapter = CityWeatherListAdapter(mutableListOf())


    //是否已经添加过
    private fun isRepetition(): Boolean = pagingAdapter.adapterData.isNotEmpty()

    //初始化城市数据
    val cities = arrayListOf(
        CityBean("北京", "110000"),
        CityBean("上海", "310000"),
        CityBean("广州", "440100"),
        CityBean("深圳", "440300"),
        CityBean("苏州", "320500"),
        CityBean("沈阳", "210100")
    )


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? = inflater.inflate(R.layout.weather_info, container, false)


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        WeatherInfoBinding.bind(view).run {
            mLayoutManager = LinearLayoutManager(WeatherApplication.getContext())
            recyclerView.run {
                layoutManager = mLayoutManager
                adapter = pagingAdapter
            }

        }

        //如果城市为空则添加城市数据
        if (!isRepetition()) {
            pagingAdapter.apply {
                setOnItemClickListener { entity ->
                    parentFragment?.let {
                        when(it) {
                            is WeatherMainFragment -> it.jumpToDetail(entity)
                        }
                    }
                }
                val start = adapterData.size
                adapterData.addAll(cities)
                notifyItemRangeInserted(start, cities.size)
            }
        }
    }




}